package com.yunxin.core.utils.infra.support.desenditized;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.yunxin.core.utils.infra.support.desenditized.annotation.DesensitizationField;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @author zero°
 * @since 2023-07-19
 */
@AllArgsConstructor
@NoArgsConstructor
public final class DesensitizedFilter extends JsonSerializer<String> implements ContextualSerializer {
    /**
     * 脱敏类型
     */
    private DesensitizedUtil.DesensitizedType type;

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (CharSequenceUtil.isEmpty(s)) {
            return;
        }
        String val;
        switch (type) {
            case CHINESE_NAME -> val = DesensitizedUtil.chineseName(s);
            case MOBILE_PHONE -> val = DesensitizedUtil.mobilePhone(s);
            case EMAIL -> val = DesensitizedUtil.email(s);
            case PASSWORD -> val = DesensitizedUtil.password(s);
            default -> val = s;
        }
        //修改数据
        jsonGenerator.writeString(val);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (ObjectUtils.isEmpty(beanProperty)) {
            return serializerProvider.findNullValueSerializer(beanProperty);
        }
        if (!Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
            return serializerProvider.findNullValueSerializer(beanProperty);
        }
        //是否有注解
        DesensitizationField annotation = beanProperty.getAnnotation(DesensitizationField.class);
        if (ObjectUtils.isEmpty(annotation)) {
            return serializerProvider.findNullValueSerializer(beanProperty);
        }
        //修改值
        return new DesensitizedFilter(annotation.type());
    }
}
